package com.adong.test;


import com.adong.test.cascade2.Customer;
import com.adong.test.cascade2.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author adong
 */
public class CascadeTest2 {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void init() {
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
    }

    @After
    public void destroy() {
        transaction.commit();
        session.close();
        sessionFactory.close();
    }

    @Test
    public void saveTest() {

        Customer customer = new Customer();
        customer.setcName("阿东");

        Orders orders1 = new Orders();
        orders1.setoName("阿东的订单1");
        orders1.setCustomer(customer);
        Orders orders2 = new Orders();
        orders2.setoName("阿东的订单2");
        orders2.setCustomer(customer);

        customer.getOrdersSet().add(orders1);
        customer.getOrdersSet().add(orders2);

        //先插1,在插多,3条insert,2条update.应为多的和1都会维护关联关系,所有多出2条update
        //在一的一段set节点设置inverse=true,让一的一段放弃维护关系
        //先插多,在插1,3条insert,4条update
        session.save(customer);
        session.save(orders1);
        session.save(orders2);
    }

    @Test
    public void getTest() {
        Customer customer = session.get(Customer.class, 1);
        System.out.println(customer.getcName());
        System.out.println(customer.getOrdersSet().getClass()); //class org.hibernate.collection.internal.PersistentSet : 作用,延迟加载,
        System.out.println(customer.getOrdersSet().size());
    }
    @Test
    public void updateTest(){
        Customer customer = session.get(Customer.class, 1);
        customer.getOrdersSet().iterator().next().setoName("二狗");
    }
}
